package com.deng.performance.dao.impl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.deng.common.SQLHelper;
import com.deng.common.vo.DispenseOrganizationVo;
import com.deng.common.vo.OrganizationVo;
import com.deng.maintenance.dao.impl.RuleEditImpl;
import com.deng.maintenance.vo.RuleGroupVo;
import com.deng.maintenance.vo.RuleVo;
import com.deng.performance.vo.DispenseBonusVo;
import com.deng.performance.vo.OrganizationFirstBonusVo;
import com.deng.util.DataFormater;
import com.deng.util.DateTools;

import flex.messaging.MessageBroker;
import flex.messaging.messages.AsyncMessage;
import flex.messaging.util.UUIDUtils;

public class NewCalculateImpl extends SQLHelper {

	public void recalYiJiHuLi(String fromD,String toD)
	{
		try
		{
			String fromDt = fromD;
			String toDt = toD;
			Calendar fromCa = Calendar.getInstance();
			fromCa.clear();
			fromCa.set(Integer.valueOf(fromDt.split("-")[0]), Integer.valueOf(fromDt.split("-")[1])-1, 1);
			Calendar toCa = Calendar.getInstance();
			toCa.clear();
			toCa.set(Integer.valueOf(toDt.split("-")[0]), Integer.valueOf(toDt.split("-")[1])-1, 1);
			
			Connection conn = getConnect();
			String sql = "select * from t_sys_stat_department where id = 275";
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{
				while(true){
					System.out.println("开始时间：  "+fromCa.getTime().toLocaleString());
					
					DispenseOrganizationVo ovo = new DispenseOrganizationVo();
//					ovo.organization_id = rs.getInt("id");
//					ovo.full_name = "其他——医技科室护理";
					ovo.id = rs.getInt("id");
					ovo.name = "其他——医技科室护理";
					ovo.stat_time_str = DateTools.dtsJustDate(fromCa.getTime());
					ovo.duty_id = rs.getInt("duty_id");
					System.out.println("计算中：   其他——医技科室护理   "+ovo.stat_time_str);
//					ovo = calOrganization(ovo,conn);
					ovo = calDispense(ovo, conn);
					
					if(fromCa.before(toCa)){
						fromCa.set(fromCa.getTime().getYear()+1900, fromCa.getTime().getMonth()+1, 1);
					}else{
						System.out.println("奖金计算完成！");						
						return;
					}
				}
				
			}
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	public void recalXingGuanHouQin(String fromD,String toD)
	{
		try
		{
			Connection conn = getConnect();
			
			
			String fromDt = fromD;
			String toDt = toD;
			Calendar fromCa = Calendar.getInstance();
			fromCa.clear();
			fromCa.set(Integer.valueOf(fromDt.split("-")[0]), Integer.valueOf(fromDt.split("-")[1])-1, 1);
			Calendar toCa = Calendar.getInstance();
			toCa.clear();
			toCa.set(Integer.valueOf(toDt.split("-")[0]), Integer.valueOf(toDt.split("-")[1])-1, 1);
			
			while(true){
				String sql = "select id,(select name from DICT_DUTY_TYPE where id = duty_id)+'--'+name as full_name,duty_id " +
						" from t_sys_stat_department where is_leaf = 1 and duty_id = 4";
				ResultSet rs = queryData(conn, sql);
				while(rs.next())
				{
					System.out.println("开始时间：  "+fromCa.getTime().toLocaleString());					
					DispenseOrganizationVo ovo = new DispenseOrganizationVo();
//					ovo.organization_id = rs.getInt("id");
//					ovo.full_name = rs.getString("full_name");
					ovo.id = rs.getInt("id");
					ovo.name = rs.getString("full_name");
					ovo.stat_time_str = DateTools.dtsJustDate(fromCa.getTime());
					ovo.duty_id = rs.getInt("duty_id");
					System.out.println("计算中：   "+ovo.name+"   "+ovo.stat_time_str);
//					ovo = calOrganization(ovo,conn);
					ovo = calDispense(ovo, conn);
				}
				updateLingDao(DateTools.dtsJustDate(fromCa.getTime()),conn);
				if(fromCa.before(toCa)){
					fromCa.set(fromCa.getTime().getYear()+1900, fromCa.getTime().getMonth()+1, 1);
				}else{
					System.out.println("奖金计算完成！");						
					return;
				}
			}
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	private void updateLingDao(String stat_time,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			String sql = "update LINGDAO_VALUE set value=dbo.FUN_LinChuangRenJunJiangJin(0,'"+stat_time+"',0,1)*0.7*jibie_fen*xishu" +
					" where stat_time = '"+stat_time+"'";
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	public DispenseOrganizationVo calOneDispense(DispenseOrganizationVo vo)
	{
		try
		{
			return calDispense(vo,getConnect());
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return vo;
	}
	
	
	public DispenseOrganizationVo calDispense(DispenseOrganizationVo vo,Connection conn)
	{//查询的唯一入口
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			System.out.println("计算合并科室："+vo.name+"  统计时间："+vo.stat_time_str);
			
			String sql = "select * from dbo.t_sys_stat_organization_vs_dispense_organization" +
					" where dispense_id = "+vo.id;
			ResultSet rs = queryData(conn, sql);
			while(rs.next())
			{				
				OrganizationFirstBonusVo ovo = new OrganizationFirstBonusVo();
				ovo.organization_id = rs.getInt("stat_id");
				ovo.stat_time_str = vo.stat_time_str;
				ovo.duty_id = rs.getInt("duty_id");
				ovo = calOrganization(ovo,conn);
			}
			updateDispenseValue(vo,conn);//更新Organization每个月数据段 状态
		}
		catch(Exception ex)
		{
			vo.status += " 异常："+ex.getMessage();
			ex.printStackTrace();
		}
		return vo;
	}
	
	public OrganizationFirstBonusVo calOrganization(OrganizationFirstBonusVo vo,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			String sql = "select dbo.GetFullOrganizationName(a.id) as fName," +
				"	a.base_bonus_function_detail as new_function," +
				"	a.duty_id" +
				"	from t_sys_stat_department  as a" +
				"	where a.id = "+vo.organization_id;
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{
				vo.full_name = rs.getString("fName");
				vo.new_function = rs.getString("new_function");
				vo.duty_id = rs.getInt("duty_id");
				vo = handleFunction(vo,conn);//名字、方法、dutyId，cal_value，monthFormula，org_id，stat_time
				updateOrganizationValue(vo,conn);//更新Organization每个月数据段 状态
				updateKPIOnMonth(vo,conn);//更新KPI分数
				return vo;
			}
			
		}
		catch(Exception ex)
		{
			vo.status += " 异常："+ex.getMessage();
			ex.printStackTrace();
		}
		return vo;
	}
	
	private OrganizationFirstBonusVo handleFunction(OrganizationFirstBonusVo vo,Connection conn)
	{
		try
		{			
			String formula = vo.new_function;
			if(formula == null || "".equals(formula))
			{
				System.out.println(vo.full_name+" 公式未设");
				vo.status = "公式未设置";
				return vo;
			}
			if(conn == null)
			{
				conn = getConnect();
			}
			//删除这一月的科室的日志
			deleteCalOrganizationLog(vo,conn);
			
			String functionWithName = getFunctionWithName(formula,conn);//中文@@公式##中文@@公式##中文@@公式##			
			StringBuffer formulaToBeCal = new StringBuffer();
			StringBuffer kpi1FormulaToBeCal = new StringBuffer();
			StringBuffer formulaCn = new StringBuffer();
//			StringBuffer formulaForKpiUpdate = new StringBuffer();
			
			for(int i = 0;i<functionWithName.split("##").length;i++)
			{
				String str = functionWithName.split("##")[i];
				if(str != null && !"".equals(str))
				{
					if(str.contains("[") )
					{formulaToBeCal.append("(");formulaCn.append("(");kpi1FormulaToBeCal.append("(");}
					else if(str.contains("]"))
					{formulaToBeCal.append(")");formulaCn.append(")");kpi1FormulaToBeCal.append(")");}
					else if(str.contains("＋"))
					{formulaToBeCal.append("+");formulaCn.append("＋");kpi1FormulaToBeCal.append("+");}
					else if(str.contains("－"))
					{formulaToBeCal.append("-");formulaCn.append("－");kpi1FormulaToBeCal.append("-");}
					else if(str.contains("×"))
					{formulaToBeCal.append("*");formulaCn.append("×");kpi1FormulaToBeCal.append("*");}
					else if(str.contains("÷"))
					{formulaToBeCal.append("/");formulaCn.append("÷");kpi1FormulaToBeCal.append("/");}
					else
					{
						
						String[] rtS = calPartFunction(vo,str,conn);//公式中文名字，公式结果
						String rtS1 = rtS[1];
						try
						{
							if(new BigDecimal(rtS1).compareTo(new BigDecimal(0))<0)
							{
								rtS1 = "("+rtS1+")";
							}
						}
						catch(Exception ex)
						{
							
						}
						if(str.indexOf("KPI") > -1)
						{
							kpi1FormulaToBeCal.append(1);//KPI中间结果
						}
						else
						{
							kpi1FormulaToBeCal.append(rtS1);//非KPI正常结果
						}
						
						formulaToBeCal.append(rtS1);//结果
						formulaCn.append(rtS[0]);//中文名字
//						if(rtS[0].indexOf("KPI") > -1)
//						{
//							formulaForKpiUpdate.append("KPI");
//						}
//						else
//						{
//							formulaForKpiUpdate.append(rtS[1]);
//						}
					}
				}
			}
			String sql = "select "+formulaToBeCal.toString();
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{				
				vo.cal_value = rs.getBigDecimal(1)!=null?rs.getBigDecimal(1).setScale(4, BigDecimal.ROUND_HALF_UP).toString():"0";
			}
			
			sql =  "select "+kpi1FormulaToBeCal.toString();;
			rs = queryData(conn,sql);
			if(rs.next())
			{				
				vo.full_value = rs.getBigDecimal(1)!=null?rs.getBigDecimal(1).setScale(4, BigDecimal.ROUND_HALF_UP).toString():"0";
			}
			
			vo.formula_value = formulaToBeCal.toString();
			vo.formula_cn = formulaCn.toString();
			return vo;
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		vo.status += " 公式计算异常";
		return vo;
	}

	//计算公式中的每个部分
	private String[] calPartFunction(OrganizationFirstBonusVo vo,String cnAndFun,Connection conn)
	{
		String calFormula ="";
		String formula = "";
		String cn = "";
		try
		{
			if(cnAndFun == null || "".equals(cnAndFun))
			{
				return new String[]{"","0"};
			}
			if(conn == null)
			{
				conn = getConnect();
			}
			formula = cnAndFun.split("@@")[1];//中文@@公式
			cn = cnAndFun.split("@@")[0];
			calFormula = formula.
				replaceAll("@organization_id", vo.organization_id+"").
				replaceAll("@duty_id", vo.duty_id+"").
				replaceAll("@stat_time", "'"+vo.stat_time_str+"'");
			if(calFormula.indexOf("UP_Period")>=0)//如果碰到点数，用规则里面定义的算，不用存储过程。
			{
				BigDecimal rtUP = getUPValue(vo,conn);
				updateOrganizationLog(vo,conn,formula,cn,rtUP.toString());
				return new String[]{cn,rtUP.toString()};
			}
			String sql = "select "+calFormula;
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{
				BigDecimal b = rs.getBigDecimal(1);
				if(b != null)
				{
					BigDecimal rt = b.setScale(4, BigDecimal.ROUND_HALF_UP);					
					updateOrganizationLog(vo,conn,formula,cn,rt.toString());
					return new String[]{cn,rt.toString()};
				}
				else
				{
					updateOrganizationLog(vo,conn,formula,cn,"0");
					return new String[]{cn,"0"};
				}
			}
		}
		catch(Exception ex)
		{
			vo.status+=" 异常函数["+calFormula+"]";	
			System.out.println("________________________   异常函数["+calFormula+"]");
//			ex.printStackTrace();
			if(calFormula.indexOf("KPI") > -1)
			{
				updateOrganizationLog(vo,conn,formula,cn,"1");
				return new String[]{cn,"1"};
			}
		}
		return new String[]{cn,"0"};
	}
	private void deleteCalOrganizationLog(OrganizationFirstBonusVo vo,Connection conn)
	{
		try
		{
			String sql = "delete t_sys_calculate_organization_log" +
					" where stat_time = '"+vo.stat_time_str+"' " +
					" and organization_id = "+vo.organization_id;
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	private void deleteCalUnitLog(OrganizationFirstBonusVo vo,Connection conn)
	{
		try
		{
			String sql = "delete t_sys_calculate_rule_log" +
					" where stat_time = '"+vo.stat_time_str+"' " +
					" and organization_id = "+vo.organization_id;
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	private void updateOrganizationLog(OrganizationFirstBonusVo vo,Connection conn,String enFormula,String cnFormula,String value)
	{
		try
		{
			String sql = "select * from t_sys_calculate_organization_log" +
					"	where stat_time ='"+vo.stat_time_str+"'" +
					"	and organization_id = "+vo.organization_id+
					"	and formula = '"+enFormula+"'";
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{
				return;
			}
			sql = "insert into t_sys_calculate_organization_log(stat_time,organization_id,name,formula,formula_cn,value,create_time)" +
						" values('"+vo.stat_time_str+"',"+vo.organization_id+",'"+vo.full_name+"','"+enFormula+"','"+cnFormula+"'," +
						" "+value+",'"+DateTools.dtsWithTime(new Date())+"')";
			
			System.out.println("记录日志: "+sql);
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
	}
	private void updateUnitLog(OrganizationFirstBonusVo vo,Connection conn,String enFormula,String cnFormula,String value)
	{
		try
		{
			String sql = "insert into t_sys_calculate_rule_log(stat_time,organization_id,name,formula,formula_cn,value,create_time)" +
						" values('"+vo.stat_time_str+"',"+vo.organization_id+",'"+vo.full_name+"','"+enFormula+"','"+cnFormula+"'," +
						" "+value+",'"+DateTools.dtsWithTime(new Date())+"')";
			
			System.out.println("记录日志: "+sql);
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
	}
	private void updateOrganizationValue(OrganizationFirstBonusVo vo,Connection conn)
	{//名字、方法、dutyId，cal_value，monthFormula，org_id，stat_time
		try
		{			
			String sql = "select * from t_stat_department_month  " +
					" where stat_time = '"+vo.stat_time_str+"'" +
					" and organization_id = "+vo.organization_id;
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{
				int valid = rs.getInt("valid");
				if(valid != 0)//已审核
				{
					sql = "update t_stat_department_month " +
						" set name = '" +vo.full_name+"', "+
						" cal_value = "+vo.cal_value+", "+
						" formula_value = '"+vo.formula_value+"',"+
						" formula_cn = '"+vo.formula_cn+"', "+
						" rule_value = '"+vo.rule_value+"',"+
						" rule_cn = '"+vo.rule_cn+"'," +
						" duty_id = "+vo.duty_id+","+
						" full_value = "+vo.full_value+
						" where stat_time = '"+vo.stat_time_str+"'" +
						" and organization_id = "+vo.organization_id;
				}
				else//未审核
				{
					sql = "update t_stat_department_month " +
							" set name = '" +vo.full_name+"', "+
							" cal_value = "+vo.cal_value+"," +
							" put_value = "+vo.cal_value+"," +
							" pay_value = "+vo.cal_value+"," +
							" formula_value = '"+vo.formula_value+"',"+
							" formula_cn = '"+vo.formula_cn+"', "+
							" rule_value = '"+vo.rule_value+"',"+
							" rule_cn = '"+vo.rule_cn+"', "+
							" duty_id = "+vo.duty_id+","+
							" full_value = "+vo.full_value+
							" where stat_time = '"+vo.stat_time_str+"'" +
							" and organization_id = "+vo.organization_id;
				}
				
			}
			else
			{
				sql = "insert into t_stat_department_month(stat_time,organization_id,name,sjly," +
						"base_bonus_function_detail,duty_id,cal_value,put_value,pay_value," +
						"valid,formula_value,formula_cn,rule_value,rule_cn,full_value)" +
						" values('"+vo.stat_time_str+"',"+vo.organization_id+","+DataFormater.valueToSQL(vo.full_name)+"," +
						"1,"+DataFormater.valueToSQL(vo.new_function)+"," +vo.duty_id+","+
						DataFormater.sqlBigDecimal(vo.cal_value)+","+
						DataFormater.sqlBigDecimal(vo.cal_value)+","+
						DataFormater.sqlBigDecimal(vo.cal_value)+","+
						"0,"+
						DataFormater.valueToSQL(vo.formula_value)+"," +
						DataFormater.valueToSQL(vo.formula_cn)+"," +
						DataFormater.valueToSQL(vo.rule_value)+"," +
						DataFormater.valueToSQL(vo.rule_cn)+"," +
						DataFormater.valueToSQL(vo.full_value)+")";
			}
			System.out.println("更新t_stat_department_month: "+sql);
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	private DispenseOrganizationVo getOrganizationValue(DispenseOrganizationVo vo,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			if(vo.valid == 1)
			{
				BigDecimal calValue = new BigDecimal(0);
				String sql = "select * from dbo.t_sys_stat_organization_vs_dispense_organization" +
					" where dispense_id = "+vo.id;
				ResultSet rs = queryData(conn, sql);
				while(rs.next())
				{
					int organization_id = rs.getInt("stat_id");
					String stat_time_str = vo.stat_time_str;
					String sq2 = "select * from t_stat_department_month" +
							" where organization_id = "+organization_id+" and stat_time = '"+stat_time_str+"'";
					ResultSet rs2 = queryData(conn, sq2);
					while(rs2.next())
					{
						BigDecimal oCalValue = rs2.getBigDecimal("cal_value");
						calValue = calValue.add(oCalValue).setScale(4, BigDecimal.ROUND_HALF_UP);
					}
				}
				vo.cal_value = calValue.toString();
				return vo;
			}
			else
			{
				BigDecimal calValue = new BigDecimal(0);
				BigDecimal putValue = new BigDecimal(0);
				BigDecimal payValue = new BigDecimal(0);
				String sql = "select * from dbo.t_sys_stat_organization_vs_dispense_organization" +
					" where dispense_id = "+vo.id;
				ResultSet rs = queryData(conn, sql);
				while(rs.next())
				{
					int organization_id = rs.getInt("stat_id");
					String stat_time_str = vo.stat_time_str;
					String sq2 = "select * from t_stat_department_month" +
							" where organization_id = "+organization_id+" and stat_time = '"+stat_time_str+"'";
					ResultSet rs2 = queryData(conn, sq2);
					while(rs2.next())
					{
						BigDecimal oCalValue = rs2.getBigDecimal("cal_value");
						calValue = calValue.add(DataFormater.sqlBigDecimal(oCalValue)).setScale(4, BigDecimal.ROUND_HALF_UP);
						BigDecimal oPutValue = rs2.getBigDecimal("put_value");
						putValue = putValue.add(DataFormater.sqlBigDecimal(oPutValue)).setScale(4, BigDecimal.ROUND_HALF_UP);
						BigDecimal oPayValue = rs2.getBigDecimal("pay_value");
						payValue = payValue.add(DataFormater.sqlBigDecimal(oPayValue)).setScale(4, BigDecimal.ROUND_HALF_UP);
					}
				}
				vo.cal_value = calValue.toString();
				vo.put_value = putValue.toString();
				vo.pay_value = payValue.toString();
				return vo;
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return vo;
	}
	private void updateDispenseValue(DispenseOrganizationVo vo,Connection conn)
	{
		try
		{
			String sql = "select * from t_stat_dispense_month  " +
					" where stat_time = '"+vo.stat_time_str+"'" +
					" and dispense_id = "+vo.id;
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{
				vo.valid = rs.getInt("valid");				
				vo = getOrganizationValue(vo,conn);
				if(vo.valid != 0)//已审核
				{
					sql = "update t_stat_dispense_month set cal_value = "+vo.cal_value+"," +
						" create_time = '"+DateTools.dtsWithTime(new Date())+"'," +
						" duty_id = "+vo.duty_id+","+
						" name = '"+vo.name+"' "+
						" where stat_time = '"+vo.stat_time_str+"'" +
						" and dispense_id = "+vo.id;
				}
				else//未审核
				{
					sql = "update t_stat_dispense_month set cal_value = "+vo.cal_value+"," +
							" put_value = "+vo.put_value+"," +
							" pay_value = "+vo.pay_value+","+
							" duty_id = "+vo.duty_id+","+
							" name = '"+vo.name+"',"+
							" create_time = '"+DateTools.dtsWithTime(new Date())+"'"+
							" where stat_time = '"+vo.stat_time_str+"'" +
							" and dispense_id = "+vo.id;
				}
				
			}
			else
			{
				vo.valid = 0;	
				vo = getOrganizationValue(vo,conn);
				sql = "insert into t_stat_dispense_month(stat_time,dispense_id,name," +
						"duty_id,cal_value,put_value,pay_value," +
						"valid,create_time)" +
						" values('"+vo.stat_time_str+"',"+vo.id+","+DataFormater.valueToSQL(vo.name)+"," +
						vo.duty_id+","+
						DataFormater.valueToSQL(vo.cal_value)+","+
						DataFormater.valueToSQL(vo.put_value)+","+
						DataFormater.valueToSQL(vo.pay_value)+","+
						"0,'"+DateTools.dtsWithTime(new Date())+"')";
			}
			System.out.println("更新t_stat_dispense_month: "+sql);
			updateData(conn, sql);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	private void updateKPIOnMonth(OrganizationFirstBonusVo vo,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			String stat_time = vo.stat_time_str;
			int oId = vo.organization_id;
			int y = Integer.valueOf(stat_time.split("-")[0]);
			int m = Integer.valueOf(stat_time.split("-")[1]);
			String sql = "";
			if(m == 1 || m == 2 )//非季度
			{//取对应季度的KPI分数
				sql = "select value from dbo.t_sys_calculate_organization_log" +
						" where year(stat_time) = " +y+
						" and month(stat_time) = " +3+
						" and organization_id = " +oId+
						" and formula_cn = 'KPI分数(0 - 1)'";
			}
			else if(m == 4 || m == 5)
			{
				sql = "select value from dbo.t_sys_calculate_organization_log" +
					" where year(stat_time) = " +y+
					" and month(stat_time) = " +6+
					" and organization_id = " +oId+
					" and formula_cn = 'KPI分数(0 - 1)'";
			}
			else if(m == 7 || m == 8 )
			{
				sql = "select value from dbo.t_sys_calculate_organization_log" +
					" where year(stat_time) = " +y+
					" and month(stat_time) = " +9+
					" and organization_id = " +oId+
					" and formula_cn = 'KPI分数(0 - 1)'";
			}
			else if(m == 10 || m == 11)
			{
				sql = "select value from dbo.t_sys_calculate_organization_log" +
					" where year(stat_time) = " +y+
					" and month(stat_time) = " +12+
					" and organization_id = " +oId+
					" and formula_cn = 'KPI分数(0 - 1)'";
			}
			else//季度
			{
				sql = "select value from dbo.t_sys_calculate_organization_log" +
					" where stat_time  = '" +stat_time+"'"+
					" and organization_id = " +oId+
					" and formula_cn = 'KPI分数(0 - 1)'";
			}
			BigDecimal kpiValue = null;
			ResultSet rs = queryData(conn, sql);
			if(rs.next())
			{	
				kpiValue = rs.getBigDecimal(1);
			}
			
			if(kpiValue != null && kpiValue.compareTo(new BigDecimal(0)) != 0)//非空且非0
			{//更新非季度的KPI扣款
				
				if((m-1)/3 == 0)//非季度
				{//取对应季度的KPI分数
					sql = "update t_stat_department_month set kpi = "+kpiValue+
						" where year(stat_time) = " +y+
						" and month(stat_time) in(1,2,3) " +
						" and organization_id = " +oId;
					updateData(conn, sql);
				}
				else if((m-1)/3 == 1)
				{
					sql = "update t_stat_department_month set kpi = "+kpiValue+
						" where year(stat_time) = " +y+
						" and month(stat_time) in(4,5,6) " +
						" and organization_id = " +oId;
					updateData(conn, sql);
				}
				else if((m-1)/3 == 2)
				{
					sql = "update t_stat_department_month set kpi = "+kpiValue+
						" where year(stat_time) = " +y+
						" and month(stat_time) in(7,8,9) " +
						" and organization_id = " +oId;
					updateData(conn, sql);
				}
				else if((m-1)/3 == 3)
				{
					sql = "update t_stat_department_month set kpi = "+kpiValue+
						" where year(stat_time) = " +y+
						" and month(stat_time) in(10,11,12) " +
						" and organization_id = " +oId;
					updateData(conn, sql);
				}				
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	private void updateOrganizationMonthRuleValue(OrganizationFirstBonusVo ovo,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	
	private BigDecimal getUPValue(OrganizationFirstBonusVo ovo,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			ResultSet rs = queryData(conn,"select g.organization_id,g.is_fee,g.name," +
					"	g.group_id as gGid,u.group_id as uGid," +
					"	g.is_mark as gMark,u.is_mark as uMark,u.fan as fan," +
					"	u.unit_id,u.type_name,u.value,g.order_operate" +
					"   from UNIT_PRICE_RULE_GROUP as g" +
					"	left join UNIT_PRICE_RULE_UNIT as u" +
					"	on g.organization_id = u.organization_id" +
					"	and g.group_id = u.group_id" +
					"	where g.organization_id = "+ovo.organization_id+
					"	order by gGid,unit_id");
			List<RuleGroupVo> l = new ArrayList<RuleGroupVo>();
			String tmpGid="";
			while(rs.next()){
				String name = rs.getString("name");
				String gGid = rs.getString("gGid");
				String uGid = rs.getString("uGid");
				int gMark = rs.getInt("gMark");
				int uMark = rs.getInt("uMark");
				int unit_id = rs.getInt("unit_id");
				int order_operate = rs.getInt("order_operate");
				int is_fee = rs.getInt("is_fee");
				int fan = rs.getInt("fan");
				String type_name = rs.getString("type_name");
				String value = rs.getString("value");
				
				if(!tmpGid.equals(gGid))
				{
					tmpGid = gGid;
					RuleGroupVo gVo = new RuleGroupVo();
					gVo.name = name;
					gVo.group_id = gGid;
					gVo.is_mark = gMark;
					gVo.order_operate = order_operate;
					gVo.is_fee = is_fee;
					List<RuleVo> l2 = new ArrayList<RuleVo>();
					
					
					RuleVo vo = new RuleVo();
					vo.is_mark = uMark;
					vo.group_id = gGid;
					vo.type_name = type_name;
					vo.value = value;
					vo.unit_id = unit_id;
					vo.fan = fan;
					l2.add(vo);
					
					gVo.ruleArr = l2;
					l.add(gVo);
				}
				else
				{
					RuleVo vo = new RuleVo();
					vo.is_mark = uMark;
					vo.group_id = gGid;
					vo.type_name = type_name;
					vo.value = value;
					vo.unit_id = unit_id;
					vo.fan = fan;
					for(int i = 0;i<l.size();i++)
					{
						RuleGroupVo tmpRg = l.get(i);
						if(tmpRg.group_id.equals(gGid))
						{
							tmpRg.ruleArr.add(vo);
							break;
						}
					}					
				}
			}
			StringBuffer formulaSB = new StringBuffer();
			StringBuffer valueSB = new StringBuffer();
			List<String[]> partValueList = new ArrayList<String[]>();	
			deleteCalUnitLog(ovo,conn);
			for(int i =0;i< l.size();i++){
				RuleGroupVo gVo = l.get(i);				
				String[] rtS = getOneRuleGroupValue(gVo,ovo, conn);
				if(rtS != null)
				{
					formulaSB.append(rtS[0]);
					valueSB.append(rtS[1]);
					partValueList.add(rtS);
				}
			}
			System.out.println(formulaSB);
			System.out.println(valueSB);
			ovo.rule_cn = formulaSB.toString();
			ovo.rule_value = valueSB.toString();
			rs = queryData(conn, "select "+valueSB.toString());
			if(rs.next())
			{
				return rs.getBigDecimal(1).setScale(4, BigDecimal.ROUND_HALF_UP);
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return new BigDecimal(0);
	}

	public String[] getOneRuleGroupValue(RuleGroupVo gVo,OrganizationFirstBonusVo ovo,Connection conn)
	{
		try
		{
			if(gVo.is_mark == 0)//计算值
			{
				StringBuffer sqlF;
				if(gVo.is_fee == 1){//用费用统计
					sqlF = new StringBuffer(" select case when sum(fee) is null then 0 else sum(fee) end" +
								" as count from t_org_organization_item_count_month" +
								" where ");
					for(int j = 0;j < gVo.ruleArr.size();j++){
						RuleVo vo = gVo.ruleArr.get(j);
						sqlF = getOneRuleUnitValueByFee(vo,sqlF,conn);
					}
					sqlF.append(
							" and stat_time >= dbo.GetPeriodDate(@stat_time,@start_time)" +
							" and stat_time <  dbo.GetPeriodDate(@stat_time,@end_time)" +
							" " );
					
				}
				else if(gVo.is_fee == 2)//用数量统计
				{
					sqlF = new StringBuffer(" select case when sum(org_item_count) is null then 0 else sum(org_item_count) end" +
										"  as count from t_org_organization_item_count_month" +
										"  where ");
					for(int j = 0;j < gVo.ruleArr.size();j++){
						RuleVo vo = gVo.ruleArr.get(j);
						sqlF = getOneRuleUnitValueByCount(vo,sqlF,conn);
					}
					sqlF.append(
							" and stat_time >= dbo.GetPeriodDate(@stat_time,@start_time)" +
							" and stat_time <  dbo.GetPeriodDate(@stat_time,@end_time)" +
							" " );
				}
				else//用项目点数
				{
					sqlF = new StringBuffer("select case when sum(a.count * b.point) is not null then sum(a.count * b.point) else 0 end from " +
							"  (" +
							"  select org_item_id,sum(org_item_count) as count from t_org_organization_item_count_month" +
							"  where ");
					for(int j = 0;j < gVo.ruleArr.size();j++){
						RuleVo vo = gVo.ruleArr.get(j);
						sqlF = getOneRuleUnitValueByPoint(vo,sqlF,conn);
					}
					sqlF.append(" and stat_time >= dbo.GetPeriodDate(@stat_time,@start_time)" +
							" and stat_time <  dbo.GetPeriodDate(@stat_time,@end_time)" +
							" group by org_item_id" +
							" ) as a," +
							" (" +
							"  select organization_id,item_id,"+(gVo.order_operate==1?"order_point":"operate_point")+" as point,is_important,duty_id " +
							"  from UNIT_PRICE_ITEM_INCOME_VS_ORGANIZATION where organization_id = @organization_id" );
//						if(key == 1){//暂时注释，因为不区分是否核心项目
//							sqlF.append(
//									"  and is_important = 1"
//							);
//									
//						}
						sqlF.append(
								"  and duty_id = @duty_id" +
								" ) as b" +
								" where a.org_item_id = b.item_id" +
								" ");
				}
				String sql = sqlF.toString().replaceAll("@organization_id", ovo.organization_id+"")
					.replaceAll("@duty_id", ovo.duty_id+"")
					.replaceAll("@stat_time", "'"+ovo.stat_time_str+"'")
					.replaceAll("@start_time", "0")
					.replaceAll("@end_time", "1");
				System.out.println(ovo.full_name+"________________________"+gVo.name+"   "+sql);
				ResultSet rs = queryData(conn, sql);
				if(rs.next())
				{					
					updateUnitLog(ovo,conn,gVo.name,gVo.name,rs.getBigDecimal(1).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
					return new String[]{gVo.name,rs.getBigDecimal(1).setScale(4, BigDecimal.ROUND_HALF_UP).toString()};
				}
			}
			else//公式
			{
				return new String[]{gVo.name,gVo.name};
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return null;
	}
	
	
	
	
	
	

	public StringBuffer getOneRuleUnitValueByFee(RuleVo vo,StringBuffer sqlF,Connection conn)
	{
		try
		{
			if(vo.is_mark == 1){//符号
				sqlF.append("   "+vo.value);
			}else{
				if(vo.fan == 1)//取反
				{
					if(vo.type_name.equals("org_order_organization_id")){									
						sqlF.append("   org_order_organization_id not in " +
								"   (select original_id from t_sys_stat_department_vs_original_department where stat_id " +
								"   in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_operate_organization_id")){
						sqlF.append("   org_operate_organization_id not in (select original_id " +
								"  from t_sys_stat_department_vs_original_department" +
								"  where stat_id in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_item_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("   org_item_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_item_name")){
						String[] strArr = vo.value.split(":");
						sqlF.append("   org_item_name not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_fee_type_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("   org_fee_type_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("sjly")){
						if(vo.value == null || vo.value.equals("")){
							System.out.println("vo.value == null");
						}else if(vo.value.equals("0")){
							sqlF.append("  sjly=0");
						}else if(vo.value.equals("1")){
							sqlF.append("  sjly=1");
						}
					}else if(vo.type_name.equals("org_order_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_order_doctor_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_operate_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_operate_doctor_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}
				}
				else
				{
					if(vo.type_name.equals("org_order_organization_id")){									
						sqlF.append("  org_order_organization_id in " +
								"  (select original_id from t_sys_stat_department_vs_original_department where stat_id " +
								"  in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_operate_organization_id")){
						sqlF.append("  org_operate_organization_id in (select original_id " +
								"    from t_sys_stat_department_vs_original_department" +
								"    where stat_id in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_item_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_item_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_item_name")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_item_name in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_fee_type_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_fee_type_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("sjly")){
						if(vo.value == null || vo.value.equals("")){
							System.out.println("vo.value == null");
						}else if(vo.value.equals("0")){
							sqlF.append("  sjly=0");
						}else if(vo.value.equals("1")){
							sqlF.append("  sjly=1");
						}
					}else if(vo.type_name.equals("org_order_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_order_doctor_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_operate_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_operate_doctor_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}
				}
				
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return sqlF;
	}
	
	public StringBuffer getOneRuleUnitValueByCount(RuleVo vo,StringBuffer sqlF,Connection conn)
	{
		try
		{
			if(vo.is_mark == 1){//小公式不是符号
				sqlF.append("  "+vo.value);
			}else{
				if(vo.fan == 1)
				{
					if(vo.type_name.equals("org_order_organization_id")){									
						sqlF.append("  org_order_organization_id not in " +
								"  (select original_id from t_sys_stat_department_vs_original_department where stat_id " +
								"  in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_operate_organization_id")){
						sqlF.append("  org_operate_organization_id not in (select original_id " +
								"    from t_sys_stat_department_vs_original_department" +
								"    where stat_id in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_item_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_item_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_item_name")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_item_name not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_fee_type_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_fee_type_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("sjly")){
						if(vo.value == null || vo.value.equals("")){
							System.out.println("vo.value == null");
						}else if(vo.value.equals("0")){
							sqlF.append("  sjly=0");
						}else if(vo.value.equals("1")){
							sqlF.append("  sjly=1");
						}
					}else if(vo.type_name.equals("org_order_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_order_doctor_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_operate_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_operate_doctor_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}
				}
				else
				{
					if(vo.type_name.equals("org_order_organization_id")){									
						sqlF.append("  org_order_organization_id in " +
								"  (select original_id from t_sys_stat_department_vs_original_department where stat_id " +
								"  in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_operate_organization_id")){
						sqlF.append("  org_operate_organization_id in (select original_id " +
								"    from t_sys_stat_department_vs_original_department" +
								"    where stat_id in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_item_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_item_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_item_name")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_item_name in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_fee_type_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_fee_type_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("sjly")){
						if(vo.value == null || vo.value.equals("")){
							System.out.println("vo.value == null");
						}else if(vo.value.equals("0")){
							sqlF.append("  sjly=0");
						}else if(vo.value.equals("1")){
							sqlF.append("  sjly=1");
						}
					}else if(vo.type_name.equals("org_order_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_order_doctor_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_operate_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append("  org_operate_doctor_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}
				}
				
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return sqlF;
	}
	
	public StringBuffer getOneRuleUnitValueByPoint(RuleVo vo,StringBuffer sqlF,Connection conn)
	{
		try
		{
			if(vo.is_mark == 1){
				sqlF.append(" "+vo.value);
			}else{
				if(vo.fan == 1)
				{
					if(vo.type_name.equals("org_order_organization_id")){
						
						sqlF.append(" org_order_organization_id not in " +
								" (select original_id from t_sys_stat_department_vs_original_department where stat_id " +
								" in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_operate_organization_id")){
						sqlF.append(" org_operate_organization_id not in (select original_id " +
								"       from t_sys_stat_department_vs_original_department" +
								"       where stat_id in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_item_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_item_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_item_name")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_item_name not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_fee_type_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_fee_type_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("sjly")){
						if(vo.value == null || vo.value.equals("")){
							System.out.println("vo.value == null");
						}else if(vo.value.equals("0")){
							sqlF.append(" sjly=0");
						}else if(vo.value.equals("1")){
							sqlF.append(" sjly=1");
						}
					}else if(vo.type_name.equals("org_order_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_order_doctor_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_operate_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_operate_doctor_id not in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}
				}
				else
				{
					if(vo.type_name.equals("org_order_organization_id")){
						
						sqlF.append(" org_order_organization_id in " +
								" (select original_id from t_sys_stat_department_vs_original_department where stat_id " +
								" in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_operate_organization_id")){
						sqlF.append(" org_operate_organization_id in (select original_id " +
								"       from t_sys_stat_department_vs_original_department" +
								"       where stat_id in("+vo.value.replaceAll(":", ",").substring(0, vo.value.length()-1)+"))");
					}else if(vo.type_name.equals("org_item_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_item_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_item_name")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_item_name in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_fee_type_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_fee_type_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("sjly")){
						if(vo.value == null || vo.value.equals("")){
							System.out.println("vo.value == null");
						}else if(vo.value.equals("0")){
							sqlF.append(" sjly=0");
						}else if(vo.value.equals("1")){
							sqlF.append(" sjly=1");
						}
					}else if(vo.type_name.equals("org_order_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_order_doctor_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}else if(vo.type_name.equals("org_operate_doctor_id")){
						String[] strArr = vo.value.split(":");
						sqlF.append(" org_operate_doctor_id in (");
						for(int k =0;k< strArr.length ;k++){
							sqlF.append("'"+strArr[k]+"',");
						}
						sqlF.delete(sqlF.length()-1, sqlF.length());
						sqlF.append(")");
					}
				}
				
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return sqlF;
	}
	private String getFunctionWithName(String str,Connection conn)
	{
		try
		{
			if(conn == null)
			{
				conn = getConnect();
			}
			String sql = "select id,function_detail as fn,function_name as name from APP_FUNCTION" +
			"	UNION ALL" +
			"	select id,function_detail as fn,function_name as name from APP_FUNCTION_OPERATE" +
			"	UNION ALL" +
			"	select id,function_detail as fn,function_name as name from APP_FUNCTION2" +
			"	UNION ALL" +
			"	select id,function_detail as fn,name from VOTE_DICT" +
			"	UNION ALL" +
			"	select id,function_detail as fn,name from VOTE_DICT2" +
			"	UNION ALL" +
			"	select id,function_detail as fn,name from VOTE_DICT_ADMIN" +
			"	UNION ALL" +
			"	select id,function_detail as fn,name from VOTE_DICT_OPERATE";
			List<String[]> l = new ArrayList();
			ResultSet rs = queryData(conn,sql);
			while(rs.next()){
				String s[] = new String[3];
				s[0] = rs.getInt("id")+"";
				s[1] = rs.getString("fn")+"";
				s[2] = rs.getString("name")+"";
				l.add(s);
			}
			StringBuffer tmpSB = new StringBuffer();
			StringBuffer wordSB = new StringBuffer();
			String nowStr = str.replaceAll(" ", "");
			int nb = 0;
			for(int i = 0;i < nowStr.length(); i++){
				String x = nowStr.charAt(i)+"";
				if(x.equals("[") || x.equals("]") || 
					x.equals("＋") || x.equals("－") || 
					x.equals("×") || x.equals("÷") ){
					String wd = getFunctionName2(tmpSB.toString(),l);
					if(!"".equals(wd)){
						wd = wd+"##";
						nb++;
					}
					wordSB.append(wd);					
					nb++;
					if(i != nowStr.length()-1)
					{
						wordSB.append(x).append("@@"+nb).append("##");
					}
					else
					{
						wordSB.append(x).append("@@"+nb);
					}					
					tmpSB = new StringBuffer();
				}else if(i == nowStr.length()-1){
					tmpSB.append(x);
					String wd = getFunctionName2(tmpSB.toString(),l);
					if(!"".equals(wd)){
						nb++;
						wordSB.append(wd);
					}
					
				}else{
					tmpSB.append(x);
				}
			}
			return wordSB.toString();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return "";
	}
		
	private String getFunctionName2(String name,List<String[]> l){	
		if(name.equals("")){
			return "";
		}
		name = name.replaceAll("'", "");
		if(name.equals("GET_DispenseBonusFormula")){
			return "科室奖金"+"@@"+name;
		}
		if(name.indexOf("dbo.UP_Period_") == 0 && name.indexOf(")") == (name.length()-1)){			   
			return "项目点数("+name.split(",")[3]+" - "+name.split(",")[4].replaceAll("\\)", "")+")@@"+name;
		}
		if(name.indexOf("dbo.KPI_Period") == 0 && name.indexOf(")") == (name.length()-1)){
			return "KPI分数("+name.split(",")[2]+" - "+name.split(",")[3].replaceAll("\\)", "")+")@@"+name;
		}
		if(name.indexOf("dbo.COST_Period") == 0 && name.indexOf(")") == (name.length()-1)){
			return "成本核算得分"+"@@"+name;
		}	
		if(name.indexOf("dbo.FUN_VOTE(") == 0 && name.indexOf(")") == (name.length()-1)){//
			String num = name.split(",")[4].replaceAll("\\)", "");
			for(int i = 0;i<l.size();i++){
				String s[] = l.get(i);
				if(s[1].startsWith("dbo.FUN_VOTE(") && s[0].equals(num)){
					return s[2]+"("+name.split(",")[2]+" - "+name.split(",")[3].replaceAll("\\)", "")+")@@"+name;
				}
			}
		}
		if(name.indexOf("dbo.FUN_VOTE2(") == 0 && name.indexOf(")") == (name.length()-1)){//
			String num = name.split(",")[5].replaceAll("\\)", "");
			for(int i = 0;i<l.size();i++){
				String s[] = l.get(i);
				if(s[1].startsWith("dbo.FUN_VOTE2(") && s[0].equals(num)){
					return s[2]+"("+name.split(",")[2]+" - "+name.split(",")[3].replaceAll("\\)", "")+")@@"+name;
				}
			}
		}
		if(name.indexOf("dbo.FUN_VOTE_OPERATE(") == 0 && name.indexOf(")") == (name.length()-1)){//
			String num = name.split(",")[4].replaceAll("\\)", "");
			for(int i = 0;i<l.size();i++){
				String s[] = l.get(i);
				if(s[1].startsWith("dbo.FUN_VOTE_OPERATE(") && s[0].equals(num)){
					return s[2]+"("+name.split(",")[2]+" - "+name.split(",")[3].replaceAll("\\)", "")+")@@"+name;
				}
			}
		}
		if(name.indexOf("dbo.FUN_VOTE_ADMIN(") == 0 && name.indexOf(")") == (name.length()-1)){//
			String num = name.split(",")[4].replaceAll("\\)", "");
			for(int i = 0;i<l.size();i++){
				String s[] = l.get(i);
				if(s[1].startsWith("dbo.FUN_VOTE_ADMIN(") && s[0].equals(num)){
					return s[2]+"("+name.split(",")[2]+" - "+name.split(",")[3].replaceAll("\\)", "")+")@@"+name;
				}
			}
		}
		if(name.indexOf(")") == (name.length()-1)){//
			String nm = name.split("\\(")[0]+"(";
			for(int i = 0;i<l.size();i++){
				String s[] = l.get(i);
				if(s[1].startsWith(nm)){
					return s[2]+"("+name.split(",")[2]+" - "+name.split(",")[3].replaceAll("\\)", "")+")@@"+name;
				}
			}
		}
		return name+"@@"+name;
	}

}
